package com.mune.gulimall.seckill.scheduled;

import com.mune.gulimall.seckill.config.KillConstant;
import com.mune.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SeckillSkuScheduled {
  @Autowired
  SeckillService seckillService;

  @Autowired
  RedissonClient redissonClient;

  /**
   * 由于分布式情况下，要防止相同的秒杀活动被同时开启，需要引入分布式锁进行处理
   */
  @Scheduled(cron = "0 * * * * ?")
  public void uploadSeckillSkuLatest3Days() throws InterruptedException {
    RLock lock = redissonClient.getLock(KillConstant.KILL_UP_LOCK);
    // 尝试获取锁，获取成功则锁上并上架秒杀活动
    boolean state = lock.tryLock(10, TimeUnit.SECONDS);
    if (state) {
      try {
        seckillService.uploadSeckillSkuLatest3Days();
        log.info("上架秒杀的商品信息");
      } finally {
        lock.unlock();
      }
    }
  }
}
